#include "Enemy.h"
#include "EnemyManager.h"
#include "TiledMapInfo.h"

Enemy::Enemy(){

}

Enemy::~Enemy(){

}

Enemy* Enemy::create(Node* node){
	auto enemy = new Enemy();
	if (enemy && enemy->init(node)){
		enemy->autorelease();
	}
	else{
		CC_SAFE_DELETE(enemy);
	}
	return enemy;
}

bool Enemy::init(Node* node){
	bool bRet = false;
	do
	{
		CC_BREAK_IF(!node);
		this->bindNode(node);
		bRet = true;
	} while (0);
	return bRet;
}

void Enemy::stop(){
	m_controller->stop();
}

void Enemy::onDead(){
	this->setContentSize(Size::ZERO);
	((EnemyManager*)(this->getParent()))->delNum();
	m_isDead = true;
	this->removeFromParentAndCleanup(true);
	this->m_controller->stop();
}

bool Enemy::setTagPosition(float x, float y){
	this->getBox(x, y);
	for (auto dstPos : a){
		Vec2 tiledPos = TiledMapInfo::tileCoorForPosition(m_map, Vec2(dstPos.x, dstPos.y));

		int tiledGid = meta->getTileGIDAt(tiledPos);

		if (tiledGid != 0){
			Value properties = m_map->getPropertiesForGID(tiledGid);
			ValueMap propertiesMap = properties.asValueMap();

			if (propertiesMap.find("Collidable") != propertiesMap.end()){
				Value prop = propertiesMap.at("Collidable");
				if (prop.asString().compare("true") == 0){

					return false;
				}
			}
		}
	}
	this->setPosition(x, y);
	return true;
}

void Enemy::setTagRotation(float rotation){
	this->setRotation(rotation);
	auto tank = (Tank*)m_node;
	tank->setHeadRotation(tank->getHeadRotation() + m_rotation - rotation);
	m_rotation = rotation;
}